package cn.huugh.handwritingdecoder;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    public static final String baseUrl = "http://10.5.46.243:8080/";
    ImageView img;
    TextView text;
    float downX = 0;
    float downY = 0;
    float upX = 0;
    float upY = 0;
    private Canvas mCanvas;
    List<MyPoint> newList = new ArrayList<>();
    private Paint mPaint;
    List<MyPoint> points = new ArrayList<>();
    public static final ExecutorService SERVICE = Executors.newSingleThreadExecutor();
    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = this.findViewById(R.id.paint);
        text = this.findViewById(R.id.number_view);

        Point point = new Point();
        getWindowManager().getDefaultDisplay().getSize(point);
        //创建一个和屏幕一样大的Bitmap
        Bitmap bitmap = Bitmap.createBitmap(point.x, point.y, Bitmap.Config.ARGB_8888);
        //创建Canvas对象
        mCanvas = new Canvas(bitmap);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(Color.WHITE);
        //将bitmap用ImageView展示
        img.setImageBitmap(bitmap);
        Gson gson = new Gson();
        img.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downX = event.getX();
                    downY = event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    upX = event.getX();
                    upY = event.getY();
                    mCanvas.drawLine(downX, downY, upX, upY, mPaint);
                    img.invalidate();
                    //更新点位
                    MyPoint point1 = new MyPoint();
                    point1.x = (int) downX;
                    point1.y = (int) downY;
                    points.add(point1);
                    downY = upY;
                    downX = upX;
                    break;
                case MotionEvent.ACTION_UP:
                    SERVICE.execute(()->{
                        try {
                            int x_max=0;
                            int y_max=0;
                            int x_min=2147483647;
                            int y_min=2147483647;
                            for(MyPoint s : points){
                                if(x_max < s.x){
                                    x_max = s.x;
                                }
                                if(y_max < s.y){
                                    y_max = s.y;
                                }
                                if(y_min > s.y){
                                    y_min = s.y;
                                }
                                if(x_min > s.x){
                                    x_min = s.x;
                                } //暴力法找出最大值最小值
                            }
                            /*System.out.println("x_max"+x_max);
                            System.out.println("y_max"+y_max);

                            System.out.println("x_min"+x_min);
                            System.out.println("y_min"+y_min);*/

                            System.out.println(points.get(1).x);
                            MyPoint firstPoint = new MyPoint();
                            firstPoint.x = x_max;
                            firstPoint.y = y_max;  // 利用已有的遍历，减小服务端处理图片的时间复杂度
                            newList.add(firstPoint); // 因此，第一个点存的是最大点
/*                            for(MyPoint s : points){ // 往左上角移动图片
                                MyPoint toSend = new MyPoint(); // 避免污染原数据
                                toSend.x = s.x-x_min;
                                toSend.y = s.y-y_min;
                                newList.add(toSend);
                            }*/
                            newList.addAll(points);
                            System.out.println(newList.toString());
                            //System.out.println(newList.get(2).x);
                            post(baseUrl+"number",gson.toJson(newList));
                            newList.clear();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                    break;
            }

            return true;

        });


        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap bitmap = Bitmap.createBitmap(point.x, point.y, Bitmap.Config.ARGB_8888);
                //创建Canvas对象
                mCanvas = new Canvas(bitmap);
                mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                mPaint.setStrokeWidth(10);
                mPaint.setColor(Color.WHITE);
                //将bitmap用ImageView展示
                img.setImageBitmap(bitmap);
                points.clear();
                Toast.makeText(getApplicationContext(), "笔迹已清除", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    void post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        //System.out.println("send");
        try (Response response = client.newCall(request).execute()) {
            String data = response.body().string();
            text.post(()->{
                    text.setText(data);
            });
        }
    }
}
